package note.learnjava;

import java.lang.reflect.Field;

/**
 * Learn Java from https://www.liaoxuefeng.com/
 * 
 * @author liaoxuefeng
 */
public class Main {

	public static void main(String[] args) throws Exception {
		Person p1 = new Person("Bob", "Beijing", 20);
		Person p2 = new Person("", "Shanghai", 20);
		Person p3 = new Person("Alice", "Shanghai", 199);
		for (Person p : new Person[] { p1, p2, p3 }) {
			try {
				check(p);
				System.out.println("Person " + p + " checked ok.");
			} catch (IllegalArgumentException e) {
				System.out.println("Person " + p + " checked failed: " + e);
			}
		}
	}

	static void check(Person person) throws IllegalArgumentException, ReflectiveOperationException {
		for (Field field : person.getClass().getFields()) {
			Range range = field.getAnnotation(Range.class);
			if (range != null) {
				Object value = field.get(person);
				//String
				if (value instanceof String){
//                    @Range(min = 1, max = 20)
//                    public String name;
//
//                    @Range(max = 10)
//                    public String city;

                    String s = (String) value;

                    if (s.length()<range.min() || s.length()>range.max()){
                        if ("".equals(s)){
                            s = "空字符串";
                        }
                        System.out.println(field.getName() +"==" +s);
                    }


                }
				//int
                if (value instanceof Integer){
                    Integer i = (Integer) value;
                    //	@Range(min = 1, max = 100)
                    if ( i < range.min() || i > range.max() ){
                        System.out.println(field.getName()+"=="+i);
                    }

                }
			}
		}
	}
}
